<template>
  <div class="user_container">
    <el-card class="box-card">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>

      <el-row class="search">
        <el-col :span="8">
          <el-input placeholder="请输入内容"
                    v-model="queryObj.query"
                    clearable
                    @clear="getUserList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button class="addUser"
                     type="primary"
                     @click="showAddDialog = true">添加用户</el-button>
        </el-col>
      </el-row>

      <template>
        <el-table :data="userList"
                  border
                  stripe>
          <el-table-column type="index">
          </el-table-column>
          <el-table-column prop="username"
                           label="姓名">
          </el-table-column>
          <el-table-column prop="email"
                           label="邮箱">
          </el-table-column>
          <el-table-column prop="mobile"
                           label="电话">
          </el-table-column>
          <el-table-column prop="role_name"
                           label="角色">
          </el-table-column>
          <el-table-column prop="mg_state"
                           label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state"
                         @change="toggleState(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作"
                           width="250px">
            <template slot-scope="scope">
              <el-button type="primary"
                         icon="el-icon-edit"
                         size="mini"
                         @click="showEditDialog(scope.row.id)"></el-button>
              <el-button type="danger"
                         icon="el-icon-delete"
                         @click="removeUser(scope.row.id)"
                         size="mini"></el-button>
              <el-button type="warning"
                         icon="el-icon-setting"
                         @click="setRole(scope.row)"
                         size="mini"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryObj.pagesize"
                     :page-sizes="[1, 2, 5, 10]"
                     :page-size="queryObj.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>

    <el-dialog title="添加用户"
               :visible.sync="showAddDialog"
               width="30%"
               @close="addUserDialog">
      <el-form label-width="100px"
               :model="addUserForm"
               :rules="addUserFormRules"
               ref="addUserFormRef"
               class="demo-ruleForm">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="showAddDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUserItem">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户信息"
               :visible.sync="showDialog"
               width="30%"
               @close="editUserInfo">
      <el-form label-width="100px"
               :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               class="demo-ruleForm">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机"
                      prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="editUserItem">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色"
               :visible.sync="showUserInfoDialog"
               @close="closeDialog"
               width="30%">
      <p>当前的用户是： {{userInfo.username}}</p>
      <p>当前的角色是： {{userInfo.role_name}}</p>
      <el-select v-model="selectRoleId"
                 placeholder="请选择角色">
        <el-option v-for="item in rolesList"
                   :key="item.id"
                   :label="item.roleName"
                   :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="showUserInfoDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
var checkEmail = (rule, value, cb) => {
  const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
  if (regEmail.test(value)) {
    return cb()
  }
  cb(new Error('请输入合法的邮箱'))
}
var checkMobile = (rule, value, cb) => {
  const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
  if (regMobile.test(value)) {
    return cb()
  }
  cb(new Error('请输入合法的手机号码'))
}

export default {
  data () {
    return {
      queryObj: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      showAddDialog: false,
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度需要控制在3-6位之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名长度需要控制在6-15位之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度需要控制在3-6位之间', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      showDialog: false,
      editForm: {},
      userInfo: {},
      rolesList: [],
      showUserInfoDialog: false,
      selectRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryObj
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户数据失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    handleSizeChange (newSize) {
      this.queryObj.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.queryObj.pagenum = newPage
      this.getUserList()
    },
    async toggleState (item) {
      const { data: res } = await this.$http.put(`users/${item.id}/state/${item.mg_state}`)
      if (res.meta.status !== 200) {
        item.mg_state = !item.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('用户状态切换成功')
    },
    addUserDialog () {
      this.$refs.addUserFormRef.resetFields()
    },
    editUserInfo () {
      this.$refs.editFormRef.resetFields()
    },
    addUserItem () {
      this.$refs.addUserFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) {
          this.$message.error('用户添加失败！')
        }
        this.$message.success('添加用户成功')
        this.showAddDialog = false
        this.getUserList()
      })
    },
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.editForm = res.data
      this.showDialog = true
    },
    editUserItem () {
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }
        this.showDialog = false
        this.getUserList()
        this.$message.success('更新用户信息成功！')
      })
    },
    async removeUser (id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // console.log('确认删除！ok')
      const { data: res } = await this.$http.delete('users/' + id)

      if (res.meta.status !== 200) {
        return this.$message.error('用户删除失败')
      }
      this.$message.success('删除用户成功！')
      this.getUserList()
    },
    async setRole (user) {
      this.userInfo = user
      console.log(this.userInfo)
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      this.showUserInfoDialog = true
    },
    async saveRoleInfo () {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败')
      }
      this.$message.success('更新用户角色成功')
      this.getUserList()
      this.showUserInfoDialog = false
    },
    closeDialog () {
      this.selectRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
.user_container {
  width: 85%;
  .search {
    margin: 15px 15px 15px 0;
  }
  .addUser {
    margin-left: 15px;
  }
  .el-pagination {
    margin-top: 15px;
  }
}
</style>
